package experiment5.task;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * @Description: 发送端
 * @author:fyl
 * @date 2021/4/22 10:00
 * @Modified By:
 * @Modified Date:
 */
public class ClientSend implements Runnable {
    //基于Socket获取的输出流对象，用于发送数据给服务器
    private DataOutputStream outputStream;
    //获取键盘输入
    private BufferedReader console;
    //判断是否连接
    private boolean connection;

    /**
     * @param socket   客户端与服务器连接的Socket对象
     * @param username 用户指定的用户名，用于服务器注册
     */
    public ClientSend(Socket socket, String username) {
        //初始化输出流和键盘输入流
        try {
            outputStream = new DataOutputStream(socket.getOutputStream());
            console = new BufferedReader(new InputStreamReader(System.in));
            //发送用户名给服务器注册
            send(username);
            connection = true;
        } catch (IOException e) {
            e.printStackTrace();
            connection = false;
            CloseUtil.closeAll(outputStream, console);
        }
    }

    /**
     * 发送数据给服务器
     *
     * @param msg 发送的数据
     */
    public void send(String msg) {
        try {
            if (msg != null && !"".equals(msg)) {
                outputStream.writeUTF(msg);
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            connection = false;
            CloseUtil.closeAll(outputStream, console);
        }
    }

    /**
     * 获取用户键盘输入的数据
     *
     * @return 用户输入的数据（字符串）
     */
    public String getMsgFromConsole() {
        String msg = null;
        try {
            msg = console.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            connection = false;
            CloseUtil.closeAll(outputStream, console);
        }
        return msg;
    }

    /**
     * 只要是连接状态一直执行发送操作
     */
    @Override
    public void run() {
        while (connection) {
            send(getMsgFromConsole());
        }
    }
}
